﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BrokerBase.Lib.Person;
using NHibernate;

namespace BrokerBase.Lib.Tool
{
    public static class PersonUtil
    {
        public static IList<IPerson> LoadBirthdayRemind(DateTime date, int preDay, ISession sess)
        {
            string d = date.ToString("yyyy-MM-dd");

            string sql = string.Format(@"select 
                                            Id,
                                            birthday, 
                                            date(birthday,'+' || (cast(strftime('%Y','{0}') as int) - cast(strftime('%Y',birthday) as int)) ||' year')as d1,
                                            date(birthday,'+' || (cast(strftime('%Y','{1}') as int) - cast(strftime('%Y',birthday) as int)+1) ||' year')as d2 
                                        from Person
                                        where 
                                            (julianday(d1)-julianday('{2}')>0 and julianday(d1)-julianday('{3}')<{4}) or 
                                            (julianday(d2)-julianday('{5}')>0 and julianday(d2)-julianday('{6}')<{7})", d, d, d, d, preDay, d, d, preDay);
            IList<object[]> cs = sess.CreateSQLQuery(sql).List<object[]>();

            string ids = "0";
            foreach (object[] o in cs)
            {
                long id = (long)o[0];
                ids += "," + id;
            }



            string hql = string.Format(@"from Person where id in({0})", ids);

            IList<IPerson> custs = sess.CreateQuery(hql).List<IPerson>();

            return custs;
        }

        public static int GetAgeFromBirthdayAndTime(DateTime birthday, DateTime time)
        {
            int age = time.Year - birthday.Year;

            if (time.Month < birthday.Month)
            {
                age--;
            }
            else if (birthday.Month == time.Month)
            {
                if (time.Day < birthday.Day)
                {
                    age--;
                }
            }
            return age;
        }

    }
}
